package com.zf.websocket.endpoint;

import com.zf.websocket.component.PortUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Zhou Feng
 */
@Slf4j
@Component
@ServerEndpoint(value = "/push/{userId}")
public class PushEndpoint {
    private static PortUtils portUtils;

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static final ConcurrentHashMap<String, PushEndpoint> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";


    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        webSocketMap.put(userId, this);


        // /push/1?username=zhang&pass=123
        // 获取路径参数 {userId -> 1}
        Map<String, String> parameters = session.getPathParameters();

        // /push/1?username=zhang&pass=123
        // 获取所有的请求参数，包括 路径参数 和 请求参数（?username=zhang&pass=123）
        // {userId -> [1], username -> [zhang], pass -> [123]}
        Map<String, List<String>> parameterMap = session.getRequestParameterMap();

        // /push/1?username=zhang&pass=123
        // 获取请求参数 :
        // username=zhang&pass=123
        String queryString = session.getQueryString();

        log.info(parameters.toString());
        log.info(parameterMap.toString());
        log.info(queryString);
    }

    @OnClose
    public void onClose(Session session) {
        webSocketMap.remove(this.userId);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("{} : {}", this.userId, message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error(error.getMessage());
    }


    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, String userId) throws IOException {
        log.info("发送消息到:" + userId + "，报文: " + message);
        PushEndpoint pushEndpoint = webSocketMap.get(userId);
        if (pushEndpoint == null) {
            log.error("用户" + userId + ",不在线！");
            return;
        }
        pushEndpoint.sendMessage(message);
    }

    /**
     * 向在线用户广播
     */
    public static void broadcast(String message) throws IOException {
        for (PushEndpoint webSocketServer : webSocketMap.values()) {
            // 异步发送
            webSocketServer.session.getAsyncRemote().sendText(message);
        }
    }


    /**
     * 解决注入问题
     */
    @Autowired
    public void setPortUtils(PortUtils portUtils) {
        PushEndpoint.portUtils = portUtils;
    }
}
